///
/// Main Javascript for nara
///

// Global variables

/**
 * User identity.
 */
var identity = {"uid": "god@paradise.dante"};

/**
 * Current active view.
 */
var active_view = null;

// Initializers

/**
 * Initiator.
 */
function overture() {
  /* If this is the first time here with no config file, 
   * a config file needs to be inserted. */
  
  alert("about to overture");
  buildWelcomeView();
  
}

// Elements creators

/**
 * Creating a generic element creator.
 */
function getNewElement(tag, style, attrs) {
  var newel = document.createElement(tag);
  
  try {
    newel.id = attrs["id"];
    newel.className = attrs["className"];
  } catch (e) {
  }
  
  for (var attr in attrs)
    if (attr != "id" && attr != "className")
      newel.attributes[attr] = attrs[attr];
    
  for (var s in style)
    newel.style[s] = style[s];
  
  return newel;
}

/**
 * Creating a generic element creator.
 */
function getNewView(id) {
  return getNewElement("div", {"background-color": "#f5f5f5", "border": "1px solid #aaaaaa"}, {"id": id});
}

/**
 * Attaching to content.
 */
function appendToContent(view) {
  var content = document.getElementById("content");
  
  var el = document.getElementById(view.id);
  if (el != null)
    content.removeChild(el);
    
  // Removes current shown view
  if (active_view != null)
    content.removeChild(document.getElementById(active_view));
  
  // Appends new view
  content.appendChild(view);
  
  // Updates the current view
  active_view = view.id;
}

// General functions

/**
 * Showing message.
 */
function showMessage(msg) {
  alert("NARA: " + msg);
}

// Data functions

/**
 * Used to connect async to a server and send data using POST HTTP.
 */
function sendDataOverHttpPost(data, url, func) {
  var http = new XMLHttpRequest();
  http.open("POST", url, true);
  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http.setRequestHeader("Content-length", data.length);
  http.setRequestHeader("Connection", "close");
  
  http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {
      func(http.responseText);
    }
  };
  
  http.send(data);
}

